package org.zxw.utils;

import com.aliyun.oss.OSS;
import com.aliyun.oss.model.PutObjectRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.net.URL;
import java.util.Date;
import java.util.UUID;

@Component
public class AliOss {
    @Autowired
    private OSS ossClient;

    @Value("${aliyun.oss.bucketName}")
    private String bucketName;

    /**
     * 上传视频到阿里云OSS
     */
    public String uploadVideoToOss(MultipartFile video) throws IOException {
        String originalFilename = video.getOriginalFilename();
        String fileExtension = originalFilename.substring(originalFilename.lastIndexOf("."));
        String objectName = "videos/" + UUID.randomUUID() + fileExtension;

        PutObjectRequest putObjectRequest = new PutObjectRequest(
                bucketName,
                objectName,
                video.getInputStream()
        );

        ossClient.putObject(putObjectRequest);
        return objectName;
    }

    /**
     * 生成URL
     */
    public String generateUrl(String objectName) {
        String url = "https://" + bucketName + "." + "oss-cn-beijing.aliyuncs.com/" + objectName;
        return url;
    }
}
